import React, { useState } from 'react';
import { Form, Select, Modal, Input, Checkbox } from 'antd';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import useControlOptions from '../../hooks/useControlOptions';
import { ButtonProps } from './Button';
import Icon from './../icon/Icon';

const screenIcon: React.CSSProperties = {
  position: 'absolute',
  right: 0,
  top: '20px'
};

const FormItem = Form.Item;
const Option = Select.Option;
const extensions = [javascript({ jsx: true })];

const typeOptions = ['primary', 'ghost', 'dashed', 'link', 'text', 'default'];
const classTypeOptions = ['save', 'submit', 'print', 'history'];
const typeOptionsMap = {
  'save': {
    text: '保存',
    textEn: 'Save',
    scriptText: `
var data = _OBJ1_;
var url = '/bk/api/lowcode/baocun/saveBigHirarchy';
console.log('data', data)
if (data) {
  showLoading()
  server({
    url:url,
    data: {
      data: data
    }
  }, function (res) {
    console.log('res', res);
    hideLoading();
    if (res.data.status === 300) {
      error(res.data.message.message);
    } else {
      next({})
      success();
    }
  })
}
    `
  },
  'submit': {
    text: '提交',
    textEn: 'Submit',
    scriptText: `
var data = _OBJ1_;
var url = '/bk/api/lowcode/baocun/saveBigHirarchy';
var goToFormName = 'System Spec Configuration-2';
data.status = '20';
console.log('data', data)
if (data) {
  showLoading()
  server({
    url: url,
    data: {
      data: data
    }
  }, function (res) {
    console.log('res', res);
    hideLoading();
    if (res.data.status === 300) {
      error(res.data.message.message);
    } else {
      next({})
      success();
      goToForm(goToFormName,{}, false)
    }
  })
}
    `
  },
  'print': {
    text: '打印',
    textEn: 'Print',
    scriptText: `
var href = location.href;
var sessionkey = 'workflow_print_source';

var formName = '';
var formId = '';

if(href.indexOf('/shell/') > -1){
  var arr = location.pathname.split('/');
  formName = decodeURIComponent(arr[arr.length-1])
}else{
  if(location.search.indexOf('?id=') > -1){
    formId = location.search.split('?id=')[1]
  }else if(location.search.indexOf('?formName=') > -1){
    formName =  decodeURIComponent(location.search.split('?formName=')[1])
  }
}

if(formId){
  setSessionStorage(sessionkey,_OBJ1_)
  open('/workflow/print?formId='+formId+'&sessionkey='+sessionkey)
}else if(formName){
  setSessionStorage(sessionkey,_OBJ1_)
  open('/workflow/print?formName='+formName+'&sessionkey='+sessionkey)
}
    `
  },
  'history': {
    text: '审批历史',
    textEn: 'Approval History',
    scriptText: `
showHistory(_OBJ1_.workFlowInstanceId);
    `
  },
};


const ButtonController = () => {
  const { options, changeControlProps, id } = useControlOptions<ButtonProps>('buttonProps');
  const [visible, setVisible] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  function show() {
    setVisible(true);
    setCodeMirrorValue(options.buttonProps?.scriptText || '');
  }

  function onOk() {
    setVisible(false);
    changeControlProps('buttonProps', {
      ...options.buttonProps,
      scriptText: codeMirrorValue
    }, true);
    setCodeMirrorValue('');
  }

  return (
    <>
      <FormItem label='控件绑定ID'>
        <Input readOnly value={id} />
      </FormItem>
      <FormItem label='风格'>
        <Select
          value={options.buttonProps?.type || 'default'}
          onChange={e => {
            changeControlProps('buttonProps', {
              ...options.buttonProps,
              type: e
            }, true);
          }}>
          {typeOptions.map(item => (
            <Option key={item} value={item}>{item}</Option>
          ))}
        </Select>
      </FormItem>
      <FormItem label='类型'>
        <Select
          allowClear
          value={options.buttonProps?.classType || ''}
          onChange={e => {
            changeControlProps('buttonProps', {
              ...options.buttonProps,
              text: typeOptionsMap?.[e]?.text || options.buttonProps.text || '按钮',
              textEn: typeOptionsMap?.[e]?.textEn || options.buttonProps.textEn || '按钮',
              classType: e || '',
              scriptText: typeOptionsMap?.[e]?.scriptText || ''
            }, true);
          }}>
          {classTypeOptions.map(item => (
            <Option key={item} value={item}>{typeOptionsMap[item].text}</Option>
          ))}
        </Select>
      </FormItem>
      <FormItem label='文字'>
        <Input
          value={options.buttonProps?.text}
          onChange={e => {
            changeControlProps('buttonProps', {
              ...options.buttonProps,
              text: e.target.value
            }, true);
          }} />
      </FormItem>

      <FormItem label='文字(EN)'>
        <Input
          value={options.buttonProps?.textEn}
          onChange={e => {
            changeControlProps('buttonProps', {
              ...options.buttonProps,
              textEn: e.target.value
            }, true);
          }} />
      </FormItem>

      <FormItem className="antd-form-item-row" label="校验必填项">
        <Checkbox
          onChange={e => {
            changeControlProps('buttonProps', {
              ...options.buttonProps,
              noCheckRequired: !e.target.checked
            }, true);
          }}
          checked={typeof options.buttonProps?.noCheckRequired === 'boolean' ? !options.buttonProps?.noCheckRequired : true} />
      </FormItem>


      <div style={{ position: 'relative' }}>
        <FormItem label='脚本内容'>
          <CodeMirror
            value={options.buttonProps?.scriptText}
            onChange={(e: string) => {
              if (window._ACTIVE_ID_ !== id) return;

              changeControlProps('buttonProps', {
                ...options.buttonProps,
                scriptText: e
              }, true);
            }} />
        </FormItem>
        <Icon
          style={screenIcon}
          icon='&#xe67c;'
          onClick={show} />
      </div>
      <Modal
        visible={visible}
        title='脚本'
        width={1000}
        onCancel={() => setVisible(false)}
        onOk={onOk}>
        <CodeMirror
          extensions={extensions}
          onChange={setCodeMirrorValue}
          value={codeMirrorValue} />
      </Modal>
    </>
  );
};

export default ButtonController;